﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Drawing;
using System.Text.RegularExpressions;
using VirtualPress.Tool.Framework;

namespace VirtualPress.Portal.WebLogic
{
    public class UploadTool
    {
        public void SWFPrepareUpload()
        {
            try
            {
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("/content/file/temp/")))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/content/file/temp/"));
                }
                var file = HttpContext.Current.Request.Files["Filedata"];
                var img = System.Drawing.Image.FromStream(file.InputStream);
                string filePathName = string.Empty;
                string newFileName = String.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid().ToString());
                filePathName = newFileName + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                bool isHorizontal = SaveAndZoom(file, HttpContext.Current.Server.MapPath("~/content/file/Temp/" + filePathName));
                //file.SaveAs(Server.MapPath("~/Customer/temp/" + filePathName));
                HttpContext.Current.Response.Write("{oldname:'" + file.FileName.Remove(file.FileName.LastIndexOf('.')) + "','name':'" + filePathName + "','path':'/content/file/temp/" + filePathName + "','horizontal':'" + isHorizontal + "'}");
            }
            catch (Exception)
            {
                HttpContext.Current.Response.StatusCode = 500;
                HttpContext.Current.Response.Write("");
            }
        }
        public bool SaveAndZoom(System.Web.HttpPostedFile postedFile, string fileName, string saveBasePath)
        {
            if (postedFile == null || postedFile.ContentLength == 0)
            {
                return false;
            }
            if (!(saveBasePath.EndsWith("/") || saveBasePath.EndsWith("\\")))
            {
                saveBasePath = saveBasePath + "\\";
            }
            return SaveAndZoom(postedFile, saveBasePath + fileName);
        }
        /// <summary>  
        /// 图片等比缩放  
        /// </summary>   
        /// <param name="postedFile">原图HttpPostedFile对象</param>  
        /// <param name="savePath">缩略图存放地址</param>  
        public bool SaveAndZoom(System.Web.HttpPostedFile postedFile, string savePath)
        {
            try
            {
                if (postedFile == null || postedFile.ContentLength == 0)
                {
                    return false;
                }
                //创建目录  
                string dir = Path.GetDirectoryName(savePath);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                //原始图片（获取原始图片创建对象，并使用流中嵌入的颜色管理信息）  
                System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true);

                double zoomHeight = 600;
                double zoomWidth = 800;
                if (initImage.Width < initImage.Height)
                {
                    //如果是平的。要求save width:1024 height:768; 
                    //否则 width:768 height: 1024
                    zoomHeight = 800;
                    zoomWidth = 600;
                }

                //缩略图宽、高计算  
                double newWidth = initImage.Width;
                double newHeight = initImage.Height;
                //宽大于高或宽等于高（横图或正方）  
                if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
                {
                    //如果宽大于模版  
                    if (initImage.Width > zoomWidth)
                    {
                        //宽按模版，高按比例缩放  
                        newWidth = zoomWidth;
                        newHeight = initImage.Height * (zoomWidth / initImage.Width);
                    }
                }
                //高大于宽（竖图）  
                else
                {
                    //如果高大于模版  
                    if (initImage.Height > zoomHeight)
                    {
                        //高按模版，宽按比例缩放  
                        newHeight = zoomHeight;
                        newWidth = initImage.Width * (zoomHeight / initImage.Height);
                    }
                }
                //生成新图  
                //新建一个bmp图片  
                System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
                //新建一个画板  
                System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);
                //设置质量  
                newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //置背景色  
                newG.Clear(Color.White);
                //画图  
                newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

                //保存缩略图                  
                newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                //释放资源  
                newG.Dispose();
                newImage.Dispose();
                initImage.Dispose();
                return true;
            }
            catch(Exception e) 
            {
                LogHelper.Write(CommonLogger.Journal, LogLevel.Error, e);
                return false;
            }
        }

        public string SaveCustomerPhoto(string photo)
        {
            string file = new Regex("/Temp/", RegexOptions.IgnoreCase).Replace(photo, "/Images/");
            file = GetNewName(HttpContext.Current.Server.MapPath(file));
            try
            {
                if (!new FileInfo(file).Directory.Exists)
                {
                    System.IO.Directory.CreateDirectory(new FileInfo(file).Directory.FullName);
                }
                System.IO.File.Copy(HttpContext.Current.Server.MapPath(photo),
                  file, false);
                System.IO.File.Delete(HttpContext.Current.Server.MapPath(photo));
                return "/" + file.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "").Replace("\\", "/");
            }
            catch { }
            return String.Empty;
        }
        private string GetNewName(string filePath, int circle = 1)
        {
            if (System.IO.File.Exists(filePath))
            {
                var fileInfo = new FileInfo(filePath);
                string name = fileInfo.Name;
                string newName = string.Empty;
                if (circle == 1) //如果是第一次递归
                {
                    newName = name.Substring(0, name.LastIndexOf('.')) + "(1)" + fileInfo.Extension;
                }
                else
                {
                    newName = name.Substring(0, name.LastIndexOf('(') + 1) + circle + ")" + fileInfo.Extension;
                }
                filePath = filePath.Replace(name, newName);
                filePath = GetNewName(filePath, ++circle);
            }
            return filePath;
        }  
    }
}
